package top.tenebrous.yzl.chat.im;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import top.tenebrous.yzl.basic.utils.ReflectionUtils;
import top.tenebrous.yzl.chat.domain.member.MMemChatRecord;
import top.tenebrous.yzl.chat.domain.member.MMemGroupUser;
import top.tenebrous.yzl.chat.domain.es.EsMemChatRecord;
import top.tenebrous.yzl.chat.mapper.member.MMemChatRecordMapper;
import top.tenebrous.yzl.chat.mapper.member.MMemGroupUserMapper;
import top.tenebrous.yzl.chat.mapper.es.EsMemChatRecordMapper;
import top.tenebrous.yzl.im.annotation.AutoConfigChatRecord;
import top.tenebrous.yzl.im.message.MessageNotice;
import top.tenebrous.yzl.im.observer.ImChatRecordHandlerProcessorObserver;
import top.tenebrous.yzl.im.utils.DateUtils;

import java.util.List;
import java.util.Objects;

/**
 * @Classname ImChatRecordObserver
 * @Description TODO
 * @Date 2023/11/10 11:24 PM
 * @Created by zhangya
 */
@Slf4j
@AutoConfigChatRecord(enableAsync = true, threadPoolClass = ThreadPoolTaskExecutor.class, enableLocalStorage = true)
@Component
public class ImChatRecordObserver implements ImChatRecordHandlerProcessorObserver<MessageNotice> {

  @Autowired
  private MMemChatRecordMapper memChatRecordMapper;

  @Autowired
  private MMemGroupUserMapper memGroupUserMapper;
  
  @Autowired
  private EsMemChatRecordMapper esMemChatRecordMapper;

  @Override
  public void onMessage(List<MessageNotice> messageNotice) {
    log.info("接收到聊天消息:{}", JSON.toJSONString(messageNotice));
    for (MessageNotice message : messageNotice) {

      if (Objects.equals(message.getChatType(), "1")) {
        log.info("公聊数据处理：{}", JSON.toJSONString(message));
        // 群聊
        List<MMemGroupUser> groupUsers = memGroupUserMapper.selectList(new LambdaQueryWrapper<MMemGroupUser>().eq(MMemGroupUser::getGroupId, message.getGroupId()));

        for (MMemGroupUser groupUser : groupUsers) {
          try {
            MMemChatRecord record = new MMemChatRecord();
            record.setFromId(StringUtils.isBlank(message.getFrom()) ? null : Long.parseLong(message.getFrom()));
            record.setToId(groupUser.getUserId());
            record.setGroupId(StringUtils.isBlank(message.getFrom()) ? null : Long.parseLong(message.getGroupId()));
            record.setChatType(2);
            record.setEnableread(0);
            if (String.valueOf(groupUser.getUserId()).equals(message.getTo())) {
              record.setEnableread(1);
            }
            record.setCreateDate(DateUtils.stringToDate(message.getCreateDate(), DateUtils.DATE_FORMAT_DATE_TIME));
            record.setContent(message.getContent());
            memChatRecordMapper.insert(record);
            
            EsMemChatRecord memChatRecord = new EsMemChatRecord();
            ReflectionUtils.copyProperties(record, memChatRecord);
            Integer esInsert = esMemChatRecordMapper.insert(memChatRecord);
            log.info("公聊保存聊天数据至es完成:{}", esInsert);
          } catch (Exception e) {
            log.error("公聊数据处理异常:{}", e);
          }
        }
        log.info("公聊数据处理：{}", JSON.toJSONString(message));

      } else {
        log.info("私聊数据处理：{}", JSON.toJSONString(message));
        // 私聊
        try {
          MMemChatRecord record = new MMemChatRecord();
          record.setFromId(StringUtils.isBlank(message.getFrom()) ? null : Long.parseLong(message.getFrom()));
          record.setToId(StringUtils.isBlank(message.getTo()) ? null : Long.parseLong(message.getTo()));
          record.setGroupId(StringUtils.isBlank(message.getGroupId()) ? null : Long.parseLong(message.getGroupId()));
          record.setChatType(1);
          record.setEnableread(message.getEnableRead());
          record.setCreateDate(DateUtils.stringToDate(message.getCreateDate(), DateUtils.DATE_FORMAT_DATE_TIME));
          record.setContent(message.getContent());
          int insert = memChatRecordMapper.insert(record);
          EsMemChatRecord memChatRecord = new EsMemChatRecord();
          ReflectionUtils.copyProperties(record, memChatRecord);
          Integer esInsert = esMemChatRecordMapper.insert(memChatRecord);
          log.info("私聊保存聊天数据至es完成:{}", esInsert);
          log.info("私聊保存聊天数据完成：{}", insert);
        } catch (Exception e) {
          log.error("私聊数据处理异常:{}", e);
        }
      }
    }
    log.info("处理聊天数据完成:{}", JSON.toJSONString(messageNotice));
  }

}
